<?php

namespace app\api\validate;

use app\common\enum\subscribe\OnSaleEnum;
use app\common\enum\subscribe\StatusEnum;
use think\Validate;

class SubscribeValidate extends Validate
{
    protected $failException = true;

    protected $rule = [
        'user_id' => 'require',
        'yearly' => 'require|checkSetting',
        'quarterly' => 'require|checkSetting',
        'monthly' => 'require|checkSetting',
        'is_on_sale' => 'number|enum:' . OnSaleEnum::class,
        'discount' => 'float',
        'promotion_text' => 'max:20',
    ];

    /**
     * 验证场景
     */
    protected $scene = [
        'subscribe' => ['user_id'],
        'settings' => ['yearly', 'quarterly', 'monthly', 'is_on_sale', 'discount', 'promotion_text'],
    ];

    public function __construct()
    {
        $this->field = [
            'user_id' => __('user_id'),
        ];
        parent::__construct();
    }

    public function checkSetting($value, $rule, $data = [], $field = ''): bool|string
    {
        if (!empty($value['status']) && !StatusEnum::tryFrom($value['status'])) {
            return $field.' '.__('invalid parameters');
        }

        $status = !empty($value['status']) && $value['status'] == StatusEnum::ENABLE->value;

        if ($status && (!is_numeric($value['price']) || $value['price'] <=0)) {
            return $field.' '.__('Please fill in the correct price');
        }

        if ($status && (!is_numeric($value['original_price']) || $value['original_price'] <=0)) {
            return $field.' '.__('Please fill in the correct original price');
        }

        return true;

    }

}